from typing import Union
from sqlalchemy.orm import Session
from db import models
from schemas.config import CreateConfigRequest, UpdateConfigRequest


class Config:
    @staticmethod
    def create(db: Session, data: CreateConfigRequest) -> models.Config:
        item = models.Config(
            created_on=data.created_on,
            created_by=data.created_by,
            name=data.name,
            data=data.data
        )
        db.add(item)
        db.commit()
        return item

    @staticmethod
    def update(db: Session, data: UpdateConfigRequest) -> None:
        db.query(models.Config).filter_by(name=data.name).update({
            "updated_on": data.updated_on,
            "updated_by": data.updated_by,
            "data": data.data,
        })
        db.commit()

    @staticmethod
    def get_by_name(db: Session, name: str) -> Union[models.Config, None]:
        return db.query(models.Config).filter_by(name=name, status=1).first()
